{% extends "base.html" %}

{% block title %}失物招领 - 校园智能生活助手{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-search text-success"></i> 失物招领</h2>
                <div>
                    <a href="{{ url_for('dashboard') }}" class="btn btn-outline-primary me-2">
                        <i class="fas fa-home"></i> 返回主页
                    </a>
                    <button type="button" class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#postItemModal">
                        <i class="fas fa-plus"></i> 发布失物信息
                    </button>
                    <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#postLostItemModal">
                        <i class="fas fa-exclamation-triangle"></i> 发布丢失物品
                    </button>
                </div>
            </div>
            
            <!-- 搜索表单 -->
            <div class="card search-card mb-4">
                <div class="card-body">
                    <form method="GET" action="{{ url_for('lost_found') }}" class="row g-3">
                        <div class="col-md-4">
                            <label for="search_item" class="form-label">
                                <i class="fas fa-box"></i> 物品名称
                            </label>
                            <input type="text" class="form-control" id="search_item" name="search_item" 
                                   placeholder="搜索物品名称" value="{{ request.args.get('search_item', '') }}">
                        </div>
                        <div class="col-md-4">
                            <label for="search_location" class="form-label">
                                <i class="fas fa-map-marker-alt"></i> 发现地点
                            </label>
                            <input type="text" class="form-control" id="search_location" name="search_location" 
                                   placeholder="搜索发现地点" value="{{ request.args.get('search_location', '') }}">
                        </div>
                        <div class="col-md-4 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                            <a href="{{ url_for('lost_found') }}" class="btn btn-outline-secondary">
                                <i class="fas fa-refresh"></i> 重置
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 失物列表 -->
    <div class="row">
        <div class="col-12">
            <!-- 搜索结果提示 -->
            {% if request.args.get('search_item') or request.args.get('search_location') %}
                <div class="search-results-info">
                    <i class="fas fa-info-circle"></i>
                    <strong>搜索结果：</strong>
                    {% if request.args.get('search_item') %}
                        物品名称包含 "{{ request.args.get('search_item') }}"
                    {% endif %}
                    {% if request.args.get('search_item') and request.args.get('search_location') %} 且 {% endif %}
                    {% if request.args.get('search_location') %}
                        发现地点包含 "{{ request.args.get('search_location') }}"
                    {% endif %}
                    ，共找到 {{ items|length }} 条记录。
                </div>
            {% endif %}
            
            {% if items %}
                <div class="row">
                    {% for item in items %}
                    <div class="col-md-6 col-lg-4 mb-4">
                        {% if item.type == 'lost' %}
                        <div class="card h-100 shadow-sm item-card lost-item-card" data-item-id="{{ item.id }}" data-finder-id="{{ item.finder_id }}" data-finder-name="{{ item.name }}" data-item-name="{{ item.item_name }}" style="cursor: pointer;">
                            <div class="card-header bg-warning text-dark">
                                <h6 class="card-title mb-0">
                                    <i class="fas fa-exclamation-triangle"></i> {{ item.item_name }}
                                </h6>
                            </div>
                            <div class="card-body">
                                <p class="card-text">
                                    <i class="fas fa-map-marker-alt text-danger"></i>
                                    <strong>丢失地点：</strong>{{ item.location }}
                                </p>
                                <p class="card-text">
                                    <i class="fas fa-user text-primary"></i>
                                    <strong>失主：</strong>{{ item.name }}
                                </p>
                                <p class="card-text">
                                    <i class="fas fa-clock text-muted"></i>
                                    <strong>发布时间：</strong>{{ item.post_time.strftime('%Y-%m-%d %H:%M') }}
                                </p>
                            </div>
                            <div class="card-footer bg-light">
                                <div class="d-flex justify-content-between align-items-center">
                                    <span class="badge bg-warning text-dark">寻找中</span>
                                    {% if session.user_id == item.finder_id %}
                                    <a href="{{ url_for('delete_lost_item_request', item_id=item.id) }}" 
                                       class="btn btn-sm btn-outline-danger"
                                       onclick="return confirm('确定要删除这条丢失物品信息吗？')">
                                        <i class="fas fa-trash"></i> 删除
                                    </a>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        {% else %}
                        <div class="card h-100 shadow-sm item-card" data-item-id="{{ item.id }}" data-finder-id="{{ item.finder_id }}" data-finder-name="{{ item.name }}" data-item-name="{{ item.item_name }}" style="cursor: pointer;">
                            <div class="card-header bg-success text-white">
                                <h6 class="card-title mb-0">
                                    <i class="fas fa-box"></i> {{ item.item_name }}
                                </h6>
                            </div>
                            <div class="card-body">
                                <p class="card-text">
                                    <i class="fas fa-map-marker-alt text-danger"></i>
                                    <strong>发现地点：</strong>{{ item.location }}
                                </p>
                                <p class="card-text">
                                    <i class="fas fa-user text-primary"></i>
                                    <strong>发布者：</strong>{{ item.name }}
                                </p>
                                <p class="card-text">
                                    <i class="fas fa-clock text-muted"></i>
                                    <strong>发布时间：</strong>{{ item.post_time.strftime('%Y-%m-%d %H:%M') }}
                                </p>
                            </div>
                            <div class="card-footer bg-light">
                                <div class="d-flex justify-content-between align-items-center">
                                    <span class="badge bg-success">可领取</span>
                                    {% if session.user_id == item.finder_id %}
                                    <a href="{{ url_for('delete_lost_item', item_id=item.id) }}" 
                                       class="btn btn-sm btn-outline-danger"
                                       onclick="return confirm('确定要删除这条失物信息吗？')">
                                        <i class="fas fa-trash"></i> 删除
                                    </a>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        {% endif %}
                    </div>
                    {% endfor %}
                </div>
            {% else %}
                <div class="text-center py-5">
                    <i class="fas fa-search fa-5x text-muted mb-3"></i>
                    <h4 class="text-muted">暂无失物信息</h4>
                    <p class="text-muted">还没有人发布失物信息，快来发布第一条吧！</p>
                    <button type="button" class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#postItemModal">
                        <i class="fas fa-plus"></i> 发布失物信息
                    </button>
                    <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#postLostItemModal">
                        <i class="fas fa-exclamation-triangle"></i> 发布丢失物品
                    </button>
                </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- 发布失物信息模态框 -->
<div class="modal fade" id="postItemModal" tabindex="-1" aria-labelledby="postItemModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title" id="postItemModalLabel">
                    <i class="fas fa-plus"></i> 发布失物信息
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{{ url_for('post_lost_item') }}" method="POST">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="item_name" class="form-label">
                            <i class="fas fa-box"></i> 物品名称 <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control" id="item_name" name="item_name" 
                               placeholder="请输入物品名称" required>
                        <div class="form-text">例如：钱包、手机、钥匙、书籍等</div>
                    </div>
                    <div class="mb-3">
                        <label for="location" class="form-label">
                            <i class="fas fa-map-marker-alt"></i> 发现地点 <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control" id="location" name="location" 
                               placeholder="请输入发现地点" required>
                        <div class="form-text">例如：图书馆三楼、食堂二楼、教学楼A座等</div>
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        <strong>温馨提示：</strong>
                        <ul class="mb-0 mt-2">
                            <li>请如实填写物品信息和发现地点</li>
                            <li>失主可通过联系方式与您取得联系</li>
                            <li>物品归还后请及时删除信息</li>
                        </ul>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times"></i> 取消
                    </button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-paper-plane"></i> 发布信息
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 发布丢失物品模态框 -->
<div class="modal fade" id="postLostItemModal" tabindex="-1" aria-labelledby="postLostItemModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning text-dark">
                <h5 class="modal-title" id="postLostItemModalLabel">
                    <i class="fas fa-exclamation-triangle"></i> 发布丢失物品
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{{ url_for('post_lost_item_request') }}" method="POST">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="lost_item_name" class="form-label">
                            <i class="fas fa-exclamation-triangle"></i> 物品名称 <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control" id="lost_item_name" name="item_name" 
                               placeholder="请输入丢失物品名称" required>
                        <div class="form-text">例如：钱包、手机、钥匙、书籍等</div>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">
                            <i class="fas fa-info-circle"></i> 物品描述
                        </label>
                        <textarea class="form-control" id="description" name="description" rows="3" 
                                  placeholder="请详细描述物品特征，有助于他人识别"></textarea>
                        <div class="form-text">例如：颜色、品牌、大小、特殊标记等</div>
                    </div>
                    <div class="mb-3">
                        <label for="lost_location" class="form-label">
                            <i class="fas fa-map-marker-alt"></i> 丢失地点 <span class="text-danger">*</span>
                        </label>
                        <input type="text" class="form-control" id="lost_location" name="lost_location" 
                               placeholder="请输入可能的丢失地点" required>
                        <div class="form-text">例如：图书馆三楼、食堂二楼、教学楼A座等</div>
                    </div>
                    <div class="mb-3">
                        <label for="lost_time" class="form-label">
                            <i class="fas fa-clock"></i> 丢失时间
                        </label>
                        <input type="datetime-local" class="form-control" id="lost_time" name="lost_time">
                        <div class="form-text">请选择大概的丢失时间</div>
                    </div>
                    <div class="mb-3">
                        <label for="contact_info" class="form-label">
                            <i class="fas fa-phone"></i> 联系方式
                        </label>
                        <input type="text" class="form-control" id="contact_info" name="contact_info" 
                               placeholder="请输入您的联系方式">
                        <div class="form-text">例如：手机号、QQ号、微信号等</div>
                    </div>
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle"></i>
                        <strong>温馨提示：</strong>
                        <ul class="mb-0 mt-2">
                            <li>请如实填写物品信息和丢失地点</li>
                            <li>详细的描述有助于他人识别您的物品</li>
                            <li>找到物品后请及时删除信息</li>
                            <li>建议留下联系方式，方便拾到者联系您</li>
                        </ul>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times"></i> 取消
                    </button>
                    <button type="submit" class="btn btn-warning">
                        <i class="fas fa-paper-plane"></i> 发布信息
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 对话模态框 -->
<div class="modal fade" id="chatModal" tabindex="-1" aria-labelledby="chatModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="chatModalLabel">
                    <i class="fas fa-comments"></i> 与 <span id="finderName"></span> 对话
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="chat-info mb-3">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        关于失物：<strong id="itemName"></strong>
                    </div>
                </div>
                <div class="chat-messages" id="chatMessages" style="height: 300px; overflow-y: auto; border: 1px solid #dee2e6; border-radius: 0.375rem; padding: 1rem; background-color: #f8f9fa;">
                    <!-- 消息将在这里显示 -->
                    <div class="text-center text-muted">
                        <i class="fas fa-comments fa-2x mb-2"></i>
                        <p>开始对话吧！</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <div class="input-group">
                    <input type="text" class="form-control" id="messageInput" placeholder="输入消息..." maxlength="500">
                    <button class="btn btn-primary" type="button" id="sendMessageBtn">
                        <i class="fas fa-paper-plane"></i> 发送
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.card {
    transition: transform 0.2s;
}

.card:hover {
    transform: translateY(-2px);
}

.badge {
    font-size: 0.8em;
}

.modal-header {
    border-bottom: none;
}

.modal-footer {
    border-top: none;
}

.alert-info {
    border-left: 4px solid #17a2b8;
}

/* 搜索表单样式 */
.search-card {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border: none;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.search-card .card-body {
    padding: 1.5rem;
}

.form-control:focus {
    border-color: #28a745;
    box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
}

.btn-primary {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    border: none;
    transition: all 0.3s ease;
}

.btn-primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
}

.btn-outline-secondary:hover {
    transform: translateY(-1px);
}

/* 搜索结果提示 */
 .search-results-info {
     background: rgba(40, 167, 69, 0.1);
     border-left: 4px solid #28a745;
     padding: 0.75rem 1rem;
     margin-bottom: 1rem;
     border-radius: 0.375rem;
 }

 /* 对话相关样式 */
 .item-card:hover {
     transform: translateY(-4px);
     box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
 }

 /* 丢失物品卡片特殊样式 */
 .lost-item-card {
     border-left: 4px solid #ffc107;
 }

 .lost-item-card:hover {
     transform: translateY(-4px);
     box-shadow: 0 8px 25px rgba(255, 193, 7, 0.3) !important;
 }

 .lost-item-card .card-header {
     background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%) !important;
 }

 .btn-warning {
     background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%);
     border: none;
     transition: all 0.3s ease;
 }

 .btn-warning:hover {
     transform: translateY(-1px);
     box-shadow: 0 4px 12px rgba(255, 193, 7, 0.3);
 }

 .chat-message {
     margin-bottom: 1rem;
     display: flex;
 }

 .chat-message.sent {
     justify-content: flex-end;
 }

 .chat-message.received {
     justify-content: flex-start;
 }

 .message-bubble {
     max-width: 70%;
     padding: 0.75rem 1rem;
     border-radius: 1rem;
     word-wrap: break-word;
 }

 .message-bubble.sent {
     background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
     color: white;
 }

 .message-bubble.received {
     background: #e9ecef;
     color: #333;
 }

 .message-time {
     font-size: 0.75rem;
     opacity: 0.7;
     margin-top: 0.25rem;
 }
</style>

<script>
let currentItemId = null;
let currentFinderId = null;
let currentItemType = 'found'; // 默认为失物招领

// 卡片点击事件
document.addEventListener('DOMContentLoaded', function() {
    const itemCards = document.querySelectorAll('.item-card');
    
    itemCards.forEach(card => {
        card.addEventListener('click', function(e) {
            // 如果点击的是删除按钮，不触发对话
            if (e.target.closest('.btn-outline-danger')) {
                return;
            }
            
            currentItemId = this.dataset.itemId;
            currentFinderId = this.dataset.finderId;
            const finderName = this.dataset.finderName;
            const itemName = this.dataset.itemName;
            
            // 判断物品类型
            currentItemType = this.classList.contains('lost-item-card') ? 'lost' : 'found';
            
            // 设置模态框信息
            document.getElementById('finderName').textContent = finderName;
            document.getElementById('itemName').textContent = itemName;
            
            // 加载消息历史
            loadMessages();
            
            // 显示模态框
            const chatModal = new bootstrap.Modal(document.getElementById('chatModal'));
            chatModal.show();
        });
    });
    
    // 发送消息事件
    document.getElementById('sendMessageBtn').addEventListener('click', sendMessage);
    document.getElementById('messageInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
});

// 加载消息历史
function loadMessages() {
    if (!currentItemId) return;
    
    fetch(`/get_messages/${currentItemId}/${currentItemType}`)
        .then(response => response.json())
        .then(data => {
            const messagesContainer = document.getElementById('chatMessages');
            
            if (data.messages && data.messages.length > 0) {
                messagesContainer.innerHTML = '';
                data.messages.forEach(message => {
                    addMessageToChat(message);
                });
            } else {
                messagesContainer.innerHTML = `
                    <div class="text-center text-muted">
                        <i class="fas fa-comments fa-2x mb-2"></i>
                        <p>开始对话吧！</p>
                    </div>
                `;
            }
            
            // 滚动到底部
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        })
        .catch(error => {
            console.error('加载消息失败:', error);
        });
}

// 发送消息
function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    
    if (!message || !currentItemId) return;
    
    fetch('/send_message', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            item_id: currentItemId,
            receiver_id: currentFinderId,
            message: message,
            item_type: currentItemType
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            messageInput.value = '';
            loadMessages(); // 重新加载消息
        } else {
            alert('发送消息失败：' + (data.error || '未知错误'));
        }
    })
    .catch(error => {
        console.error('发送消息失败:', error);
        alert('发送消息失败，请稍后重试');
    });
}

// 添加消息到聊天界面
function addMessageToChat(message) {
    const messagesContainer = document.getElementById('chatMessages');
    const currentUserId = '{{ session.user_id }}';
    const isSent = message.sender_id === currentUserId;
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `chat-message ${isSent ? 'sent' : 'received'}`;
    
    const bubbleDiv = document.createElement('div');
    bubbleDiv.className = `message-bubble ${isSent ? 'sent' : 'received'}`;
    
    const messageText = document.createElement('div');
    messageText.textContent = message.message;
    
    const timeDiv = document.createElement('div');
    timeDiv.className = 'message-time';
    timeDiv.textContent = new Date(message.sent_time).toLocaleString('zh-CN');
    
    bubbleDiv.appendChild(messageText);
    bubbleDiv.appendChild(timeDiv);
    messageDiv.appendChild(bubbleDiv);
    
    messagesContainer.appendChild(messageDiv);
}
</script>
{% endblock %}